package com.feiwo.nonego.rpc.protocol.base;

import com.feiwo.nonego.rpc.common.util.MessageIdGenerator;
import com.feiwo.nonego.rpc.common.util.snowflake.SnowflakeIdGenerator;

import java.util.function.Supplier;

/**
 * @author feiwo 2025-08-05
 */
public class MessageIdGeneratorFactory {

    private static final MessageIdGenerator defaultGenerator;
    private static Supplier<MessageIdGenerator> customGeneratorSupplier;

    static {
        // 初始化默认生成器（雪花算法）
        long workerId = Long.parseLong(System.getProperty("snowflake.workerId", "1"));
        long datacenterId = Long.parseLong(System.getProperty("snowflake.datacenterId", "1"));
        defaultGenerator = new SnowflakeIdGenerator(workerId, datacenterId);
    }

    /**
     * 设置自定义生成器供应商
     * @param generatorSupplier 自定义生成器供应商
     */
    public static void setCustomGenerator(Supplier<MessageIdGenerator> generatorSupplier) {
        customGeneratorSupplier = generatorSupplier;
    }

    /**
     * 生成消息ID
     * @return 消息ID
     */
    public static long generate() {
        if (customGeneratorSupplier != null) {
            return customGeneratorSupplier.get().generate();
        }
        return defaultGenerator.generate();
    }

    /**
     * 获取当前使用的生成器实例
     * @return 消息ID生成器实例
     */
    public static MessageIdGenerator getCurrentGenerator() {
        if (customGeneratorSupplier != null) {
            return customGeneratorSupplier.get();
        }
        return defaultGenerator;
    }

}
